<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="">
            <el-input
              v-model="foodName"
              size="medium"
              placeholder="查询用户名"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              size="small"
              type="success"
              @click="production"
              icon="el-icon-search"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item label="">
            <el-button
              size="small"
              type="warning"
              @click="notEmpty"
              icon="el-icon-delete-solid"
              >清空</el-button
            >
          </el-form-item>
          <el-form-item label="">
            <el-button
              size="small"
              type="primary"
              @click="addition(1)"
              icon="el-icon-plus"
              >新建</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="24">
        <el-table
          :data="tableData"
          border
          v-loading="loadFlag"
          style="width: 100%"
        >
          <el-table-column prop="name" label="用户名" align="center">
          </el-table-column>

          <el-table-column prop="phone" label="手机号" align="center">
          </el-table-column>
          <el-table-column prop="mailbox" label="邮箱" align="center">
          </el-table-column>
          <el-table-column prop="departId" label="部门" align="center">
          </el-table-column>
          <el-table-column prop="roleId" label="角色" align="center">
          </el-table-column>
          <el-table-column label="操作" width="240" align="center">
            <template #default="scope">
              <el-button size="mini" @click="handleEdit(scope.row, 2)"
                >编辑</el-button
              >
              <el-button size="mini" type="danger" @click="deleted(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagingClass">
          <el-pagination
            :page-sizes="m_page.sizes"
            :page-size="m_page.size"
            :current-page="m_page.number"
            @size-change="m_handleSizeChange"
            @current-change="m_handlePageChange"
            layout="total,sizes,prev, pager, next"
            background
            :total="m_page.totalElements"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog
      :title="single"
      v-model="plassets"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="用户名" prop="userIds">
          <el-input v-model="form.userIds" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            show-password
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="superior">
          <el-cascader
            :show-all-levels="false"
            style="width: 300px"
            clearable
            v-model="form.superior"
            :options="department"
            :props="{ checkStrictly: true }"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="form.mrole"
            placeholder="请选择"
            style="width: 300px"
          >
            <el-option
              v-for="item in itemRole"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="plassets = false">取 消</el-button>
          <el-button type="primary" v-if="under == 1" @click="Determine('form')"
            >确 定</el-button
          >
          <el-button type="primary" v-else @click="hardware('form')"
            >编辑确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "upload",
  data() {
    return {
      single: "新增用户",
      foodName: "",
      plassets: false,
      form: {
        userIds: "",
        phone: "",
        email: "",
        password: "", //密码
        mrole: "", //角色
        superior: [], //部门
      },
      loadFlag: false, //加载flag
      rules: {
        userIds: [
          { required: true, message: "请输入用户名", trigger: "change" },
        ],
        phone: [
          { required: true, message: "请输入电话号码", trigger: "change" },
        ],
        password: [
          { required: true, message: "请输入登录密码", trigger: "change" },
        ],
        // mrole: [{ required: true, message: "请选择角色", trigger: "change" }],
        superior: [
          { required: true, message: "请选择部门", trigger: "change" },
        ],
      },
      itemRole: [
        {
          value: "0",
          label: "超级管理员",
        },
        {
          value: "1",
          label: "普通员工",
        },
      ],
      tableData: [],
      department: [],
      m_page: {
        sizes: [10, 20, 40, 50, 100], //每页最大显示数
        size: 10,
        totalElements: 0,
        totalPages: 3,
        number: 1,
      },
      under: 1,
      underID: "",
      headerObj: "", //请求头
      editors: "",
    };
  },
  created() {
    let str = sessionStorage.getItem("token");
    // this.headerObj["Authorization"] = `Bearer ${str}`;
    this.headerObj = `Bearer ${str}`;
  },
  beforeMount() {
    this.Acquisition();
    this.production(); //获取用户
  },
  components: {},
  methods: {
    addition(index) {
      this.under = index;
      this.plassets = true;
      this.form.userIds = "";
      this.form.phone = "";
      this.form.email = "";
      this.form.password = "";
      this.form.superior = [];
      this.form.mrole = "";
    },
    //编辑
    handleEdit(row, index) {
      console.log(row);
      this.under = index;
      this.plassets = true;
      this.underID = row.id;
      this.form.userIds = row.name;
      this.form.phone = row.phone;
      this.form.email = row.mailbox;
      this.form.password = row.password;
      this.form.superior = row.departId;
      this.editors = row.departId;
      this.form.mrole = row.roleId;
    },
    handleChange() {
      // console.log(value);
      if (this.form.superior.length == 1) {
        this.editors = this.form.superior[0];
      } else if (this.form.superior.length == 2) {
        this.editors = this.form.superior[1];
      } else if (this.form.superior.length == 3) {
        this.editors = this.form.superior[2];
      }
      console.log(this.editors);
    },
    hardware(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          // alert("submit!");
          // if (this.superior.length == 1) {
          //   this.editors = this.superior[0];
          // } else if (this.superior.length == 2) {
          //   this.editors = this.superior[1];
          // } else if (this.superior.length == 3) {
          //   this.editors = this.superior[2];
          // }
          this.$axios
            .post(
              `api/serial/Users`,
              {
                id: this.underID,
                name: this.form.userIds,
                phone: this.form.phone,
                mailbox: this.form.email,
                password: this.form.password,
                roleId: 0, //角色
                departId: this.editors, //部门ID
              },
              {
                headers: {
                  Authorization: this.headerObj,
                },
              }
            )
            .then(() => {
              this.$message({
                message: "编辑成功",
                type: "success",
              });
              this.plassets = false;
              this.production();
            })
            .catch(() => {
              this.$message.error("编辑失败");
            });
        } else {
          return false;
        }
      });
    },
    Determine(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          // alert("submit!");

          this.$axios
            .post(
              `api/serial/Users`,
              {
                name: this.form.userIds,
                phone: this.form.phone,
                mailbox: this.form.email,
                password: this.form.password,
                roleId: 0, //角色
                departId: this.editors, //部门ID
              },
              {
                headers: {
                  Authorization: this.headerObj,
                },
              }
            )
            .then((res) => {
              console.log(res);
              this.$message({
                message: "保存成功",
                type: "success",
              });
              this.production();
              this.plassets = false;
            })
            .catch(() => {
              this.$message.error("保存失败");
            });
        } else {
          return false;
        }
      });
    },
    //删除
    deleted(row) {
      console.log(row);
      let into = row;
      this.$confirm("确认删除该设备?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .post(
              `api/serial/Users`,
              {
                id: into.id,
                name: into.name,
                phone: into.phone,
                mailbox: into.mailbox,
                password: into.password,
                roleId: 0,
                departId: 0,
                isDelete: 1,
              },
              {
                headers: {
                  Authorization: this.headerObj,
                },
              }
            )
            .then(() => {
              // console.log(res);
              this.production();
              this.$message.success("删除成功");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    notEmpty() {
      this.foodName = "";
      this.production();
    },
    production() {
      this.loadFlag = true;
      this.$axios({
        methods: "GET",
        url: "api/serial/Users",
        headers: {
          Authorization: this.headerObj,
        },
        params: {
          pageSize: this.m_page.size,
          pageIndex: this.m_page.number,
          query: {
            // equipmentNumber: this.foodName,
            name: this.foodName,
            // model: this.foodName,
            // managementId: this.foodName,
          },
        },
      }).then((res) => {
        ({ data: this.tableData, count: this.m_page.totalElements } = res.data);
        this.loadFlag = false;
      });
    },
    //页码
    m_handlePageChange(currPage) {
      this.m_page.number = currPage;
      this.production();
    },
    m_handleSizeChange(currSize) {
      this.m_page.size = currSize;
      this.production();
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    //获取上级部门
    Acquisition() {
      this.$axios
        .get(`api/serial/DepartmentTree`, {
          headers: {
            Authorization: this.headerObj,
          },
        })
        .then((res) => {
          // console.log(res);
          this.fication = res.data.data;
          // console.log(this.fication);
          let arr = [];
          this.fication.forEach((item, index) => {
            console.log(item);
            arr[index] = {
              value: item.id,
              label: item.departName,
            };

            if (item.departmentList) {
              arr[index].children = [];
              item.departmentList.forEach((item1, index1) => {
                arr[index].children[index1] = {
                  value: item1.id,
                  label: item1.departName,
                };
                arr[index].children[index1].children = [];
                item1.departmentList.forEach((item2, index2) => {
                  arr[index].children[index1].children[index2] = {
                    value: item2.id,
                    label: item2.departName,
                  };
                });
              });
            }
          });
          console.log(arr);
          this.department = arr;
        });
    },
  },
};
</script>

<style scoped>
.pagingClass {
  text-align: right;
  height: 40px;
  line-height: 40px;
  /* margin: 20px 0; */
  background-color: #fff;
  margin-bottom: 40px;
}
</style>